package com.ljfresh.customer.controller;

import com.alibaba.fastjson.JSONObject;
import com.ljfresh.customer.data.GoodsOrderFidData;
import com.ljfresh.customer.erp.ERPBasicAPIUtil;
import com.ljfresh.customer.erp.ERPConsts;
import com.ljfresh.customer.erp.ERPParamBuilder;
import com.ljfresh.customer.page.PageObject;
import com.ljfresh.customer.page.PageResult;
import com.ljfresh.customer.pojo.AbnormalGoods;
import com.ljfresh.customer.pojo.ErpGoods;
import com.ljfresh.customer.result.*;
import com.ljfresh.customer.sercice.AbnormalGoodService;
import com.ljfresh.customer.sercice.ErpGoodsService;
import com.ljfresh.customer.utils.JacksonUtil;
import com.ljfresh.customer.utils.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: Lucifer
 * @time: 2020/4/6-11:43
 */
@Api(value = "异常商品",tags = "异常商品模块接口")
@RestController
@RequestMapping("/abnormalGoods")
public class AbnormalGoodsController {

    public static void main(String[] args) {
        List<Integer> list = new ArrayList();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(6);
        list.add(7);
        list.add(8);
        list.add(9);
        List<Integer> list1 = list.subList(2, 4);
        List<Integer> list2 = new ArrayList(list1);
        for (Integer aaa : list2){
            System.out.println(aaa);
        }
    }

    @Resource
    private AbnormalGoodService abnormalGoodService;

    @Resource
    private ErpGoodsService erpGoodsService;

    @Resource
    private RedisUtils redisUtils;

    @GetMapping("/transferIn")
    @ApiOperation("查询调入单接口")
    @ApiResponses({
            @ApiResponse(code = 200,message = "请求成功"),
            @ApiResponse(code = 400,message = "参数错误"),
            @ApiResponse(code = 405003,message = "参数错误"),
            @ApiResponse(code = 402001,message = "没有调入单")
    })
    public RransferInGoodsResult TransferIn(@RequestParam(value = "storeCode")String storeCode,
                                            @RequestParam(value = "date",required = false) String datestr) throws Exception{
        Date date = new Date();
        if (datestr!=null && !datestr.equals("")){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
            date = simpleDateFormat.parse(datestr);
        }

        TokenResult tokenResult = JSONObject.parseObject(redisUtils.get(ERPConsts.erpTokenRedisKey).toString(), TokenResult.class);
        if (tokenResult!=null){
            List<FindTransferinResult> transferin = ERPBasicAPIUtil.transferin(tokenResult.getRefresh_token(), storeCode,date);
            if (transferin.size()>0){
                for (FindTransferinResult findTransferinResult : transferin) {
                    redisUtils.set(findTransferinResult.getIn_order_fid(),findTransferinResult.getDetails());
                    findTransferinResult.setDetails(null);
                }
                return new RransferInGoodsResult(transferin);
            }else{
                return new RransferInGoodsResult(402001);
            }
        }
        return new RransferInGoodsResult(005001);
    }

    @GetMapping("/findGoodsByOrderFid")
    @ApiOperation("查询调入单商品接口")
    @ApiResponses({
            @ApiResponse(code = 200,message = "请求成功"),
            @ApiResponse(code = 400,message = "参数错误"),
            @ApiResponse(code = 405003,message = "参数错误"),
            @ApiResponse(code = 402005,message = "查询调入单商品失败"),
            @ApiResponse(code = 402006,message = "查询调入单商品为空")
    })
    public FindGoodsOrderFidResult findGoodsByOrderFid(@RequestParam(value = "orderFid") String orderFid,
                                                       @RequestParam(value = "name") String name,
                                                       @RequestParam(value = "pageNo") Integer pageNo,
                                                       @RequestParam(value = "pageSize") Integer pageSize){
        List<TransferinDetailsResult> transferinDetailsResults = null;
        List<TransferinDetailsResult> transferinDetails = new ArrayList<>();
        if (orderFid==null||orderFid.equals("")){
            return new FindGoodsOrderFidResult(405003);
        }
        try {
            if (redisUtils.get(orderFid)!=null&&!redisUtils.get(orderFid).equals("")){
                String str = redisUtils.get(orderFid).toString();
                transferinDetailsResults =
                        JacksonUtil.convertList(str, TransferinDetailsResult.class);
                transferinDetailsResults.forEach(result ->{
                    Pattern pattern = Pattern.compile(name);
                    Matcher matcher = pattern.matcher(result.getItem_name());
                    if(matcher.find()){
                        System.out.println(result.getItem_name());
                        transferinDetails.add(result);
                    }
                });
                GoodsOrderFidData goodsOrderFidData = new GoodsOrderFidData();
                goodsOrderFidData.setPageNo(pageNo);
                goodsOrderFidData.setPageSize(pageSize);
                goodsOrderFidData.setTotalCount(transferinDetails.size());
                List<ErpGoods> erpGoodsList = new ArrayList<>();
                Integer num = (pageNo - 1) * pageSize;
                Integer numTo = num+pageSize;
                if (num>transferinDetails.size()) {
                    return new FindGoodsOrderFidResult(402005);
                }else if (numTo > transferinDetails.size()){
                    numTo = transferinDetails.size();
                }
                List<TransferinDetailsResult> results = new ArrayList<>(transferinDetails.subList(num, numTo));
                for (TransferinDetailsResult result:results) {
                    ErpGoods erpGoods = new ErpGoods();
                    erpGoods.setGoodsId(Integer.parseInt(result.getItem_code()));
                    erpGoods.setGoodsName(result.getItem_name());
                    erpGoods.setGoodsUnit(result.getItem_unit());
                    erpGoods.setGoodsNum(result.getItem_qty());
                    erpGoods.setPricePerUnit(result.getItem_price());
                    erpGoodsList.add(erpGoods);
                }
                goodsOrderFidData.setList(erpGoodsList);
                return new FindGoodsOrderFidResult(goodsOrderFidData);
            }else{
                return new FindGoodsOrderFidResult(402006);
            }
        }catch (Exception e){
            e.printStackTrace();
            return new FindGoodsOrderFidResult(402005);
        }
    }

    @GetMapping("/findErpGoods")
    @ApiOperation("查询ERP商品接口")
    @ApiResponses({
            @ApiResponse(code = 200,message = "请求成功"),
            @ApiResponse(code = 400,message = "参数错误"),
            @ApiResponse(code = 402002,message = "没有ERP商品"),
            @ApiResponse(code = 402004,message = "查询ERP商品失败")
    })
    public ErpGoodsResult findErpGoods(@RequestParam(value = "name",required = false) String name,
                                       @RequestParam("pageNo") Integer pageNo,
                                       @RequestParam("pageSize") Integer pageSize){
        Map map = new HashMap();
        try {
            if (name!=null && !name.equals("")){
                map.put("likeGoodsName",name);
            }
            PageObject pageObject = new PageObject();
            pageObject.setPageNumber((pageNo-1)*pageSize);
            pageObject.setPageSize(pageSize);
            pageObject.setMap(map);
            PageResult<ErpGoods> abnormalGoods = erpGoodsService.findByPage(pageObject);
            if (abnormalGoods.getList().size()>0){
                return new ErpGoodsResult(abnormalGoods);
            }else{
                return new ErpGoodsResult(402002);
            }
        }catch (Exception e){
            e.printStackTrace();
            return new ErpGoodsResult(402004);
        }
    }
}
